package dxunderground.winampController.Server;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.PriorityQueue;

import dxunderground.utilities.math.Random;

@SuppressWarnings("serial")
public class PlaylistQueue extends PriorityQueue<File> implements Runnable {
	private Playlist playlist;
	private ArrayList<File> songs;
	private Runtime rt;

	public static boolean progRun = true;
	public static boolean auto = false;

	public PlaylistQueue(Playlist playlist, Runtime rt) {
		this.playlist = playlist;
		this.songs = playlist.getSongs();
		this.rt = rt;
	}

	public void run() {
		while (progRun) {
			while (progRun && auto) {
				if (!songs.isEmpty()) {
					boolean status = playlist.notifyWhenReady();
					if (status && this.isEmpty()) {
						play(Random.randomCap(songs.size() - 1));
						playlist.nextSong();
						playlist.playPauseSong();
					} else if (status) {
						play(this.remove().getPath());
						playlist.nextSong();
						playlist.playPauseSong();
					}
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void play(String path) {
		try {
			rt.exec("C:/Program Files/Winamp/winamp.exe /add \"" + path + "\"");
			Thread.sleep(50); // Prevents comp crashing
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	private void play(int songNum) {
		play(this.songs.get(songNum).getPath());
	}
}